<?php

class UserAccess {

    static $database;

    /**
     * Set Database pointer to database used for User logins
     * @param type $db 
     */
    static function initDatabase($db) {
        self::$database = $db;
    }

    /**
     *
     * @param type $memberId
     * @param type $username
     * @param type $password , password is already hashed
     * $rememberMe , Set to 1 if user should be logged in next time
     */
    static function createsessions($memberId, $username, $password, $rememberMe) {
        //Add additional member to Session array as per requirement 
        session_register();

        $_SESSION["memberId"] = $memberId;        
        $_SESSION["username"] = $username;
        $_SESSION["password"] = $password;
        
        //Get Admin-status for user
        $sth = self::$database->prepare("SELECT admin FROM Members WHERE memberId=:memberId");
        $sth->execute(array(
          ':memberId' => $memberId,
        ));

        $data = $sth->fetch();

        $admin = $data['admin'];
        $_SESSION["admin"] = $admin;

        if ($rememberMe) {
//Add additional member to cookie array as per requirement 
            setcookie("memberId", $_SESSION['memberId'], time() + 60 * 60 * 24 * 100, "/");
            setcookie("username", $_SESSION['username'], time() + 60 * 60 * 24 * 100, "/");
            setcookie("password", $_SESSION['password'], time() + 60 * 60 * 24 * 100, "/");
            return;
        }
    }

    /**
     * Remove current user from Session and cookie 
     */
    static function clearsessionscookies() {
        unset($_SESSION['memberId']);
        unset($_SESSION['username']);
        unset($_SESSION['password']);

        session_unset();
        session_destroy();

        setcookie("memberId", "", time() - 60 * 60 * 24 * 100, "/");
        setcookie("username", "", time() - 60 * 60 * 24 * 100, "/");
        setcookie("password", "", time() - 60 * 60 * 24 * 100, "/");
    }

    /**
     * Hash function for password
     * @param type $password unhashed password
     * @return type  hashed password
     */
    static function passwordHash($password) {
        return md5($password);
    }

    /**
     *
     * Set _SESSION['msg']['login-err'] if there is a login error
     * 
     * @param type $username
     * @param string $password , without hash
     *
     * @return boolean , true if user and password is correct
     */
    static function confirmUser($username, $password) {

        $err = array(); // Will hold our errors        

        if (!$username || !$password)
            $err[] = 'All the fields must be filled in!';

        
        //Check if database is enabled
        if(!isset(self::$database))
            return false;
            
        if (!count($err)) {
            $memberId = self::getMemberId($username, $password);

            if (!$memberId) // A user does not exist
                $err[] = 'Wrong username and/or password!';
        }

        if ($err) { //Check if login had an error
            $_SESSION['msg']['login-err'] = implode('<br />', $err);
            return false;
        }
        else
            return true;

        return false;
    }

    /**
     * Return Member id from db. If no user exists isset is false
     * @param type $username
     * @param type $password
     * @return type 
     */
    static function getMemberId($username, $password) {
        /* Validate from the database  */
                
        $sth = self::$database->prepare("SELECT memberId FROM Members WHERE username=:username AND passwordHash=:password");
        $sth->execute(array(
          ':username' => $username,
          ':password' => self::passwordHash($password)
        ));

        $data = $sth->fetch();

        $memberId = $data['memberId'];
        
        return $memberId;
    }
    
    
    /**
     * Change current users password, if current and new password are ok
     * @param type $currentpassword
     * @param type $newpassword
     * @param type $repeatnewpassword 
     */
    static function changeUserPassword($currentpassword, $newpassword, $repeatnewpassword) {

        $err = array();

//All fields should have text
        if (!$currentpassword || !$newpassword || !$repeatnewpassword) {
            $err[] = 'All the fields must be filled in!';
        }

//Check new password are the same
        if (!count($err) && strcmp($newpassword, $repeatnewpassword) != 0) {
            $err[] = 'New passwords do not match!';
        }

//Check new password length
        if (!count($err) && strlen($newpassword) < 4 || strlen($newpassword) > 32) {
            $err[] = 'Your new password must be between 3 and 32 characters!';
        }

//Check current password
        if (!count($err) && strcmp($_SESSION['password'], $currentpassword) != 0) {
            $err[] = 'Current password is not correct!';
        }

//Everything is fine, update password
        if (!count($err)) {
            $sth = self::$database->prepare("UPDATE Members SET passwordHash=:passwordHash WHERE username='" . $_SESSION['username']."'");
            $sth->execute(array(
                ':passwordHash' => self::passwordHash($newpassword)
            ));
        }
//Formate error message
        if (count($err)) {
            $_SESSION['msg']['newpassword-err'] = implode('<br />', $err);
        }
    }

    /**
     * Register new user 
     */
    static function registerUser($username, $email) {
// If the Register form has been submitted

        $err = array();

        if (strlen($username) < 3 || strlen($username) > 32) {
            $err[] = 'Your username must be between 4 and 32 characters!';
        }

        if (preg_match('/[^a-z0-9\-\_\.]+/i', $username)) {
            $err[] = 'Your username contains invalid characters!';
        }

        if (!self::checkEmail($email)) {
            $err[] = 'Your email is not valid!';
        }

        if (!count($err)) {
// If there are no errors, check if user exists

            $sth = self::$database->prepare("SELECT memberId FROM Members WHERE username=:username");
            $sth->execute(array(
                ':username' => $username,
            ));

            $data = $sth->fetch();

            $memberId = $data['memberId'];

            if ($memberId) // A user does not exist
                $err[] = 'This username is already taken!';
        }

        if (!count($err)) {
//If there are no erros  Generate a random password    
            $pass = substr(md5($_SERVER['REMOTE_ADDR'] . microtime() . rand(1, 100000)), 0, 6);
            $passHash = self::passwordHash($pass);
//Insert user in database
            $sth = self::$database->prepare("INSERT INTO Members(username,passwordHash,email,dateTime)
                        VALUES(:username , :password, :email, NOW())");
            $sth->execute(array(
                ':username' => $username,
                ':password' => $passHash,
                ':email' => $email
            ));

//Send email to User
            self::send_mail('picksplayer@gmail.com', $email, 'Registration for Picks Players - Your New Password', 'Your password is: ' . $pass);
            $_SESSION['msg']['reg-success'] = 'We sent you an email with your new password!';
        }

        if (count($err)) {
            $_SESSION['msg']['reg-err'] = implode('<br />', $err);
        }
    }

    /**
     * Return true if user is logged in or cookie is set to be logged in 
     * 
     * @return boolean 
     */
    static function checkLoggedin() {
        if (isset($_SESSION['memberId']) AND isset($_SESSION['username']) AND isset($_SESSION['password']))
            return true;
        elseif (isset($_COOKIE['memberId']) && isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
            if (self::confirmUser($_COOKIE['username'], $_COOKIE['password'])) {
                self::createsessions($_COOKIE['memberId'], $_COOKIE['username'], $_COOKIE['password'], 1);
                return true;
            } else {
                return false;
            }
        }
        else
            return false;
    }
    
    static function GetMobileViewer() {
        //Check if Session is set
        if(isset($_SESSION['MobileViewer']))
            return $_SESSION['MobileViewer'];
        //Check if Cookie is set
        if (isset($_COOKIE['MobileViewer']))
        {
            $_SESSION['MobileViewer'] = $_COOKIE['MobileViewer'];
            return $_SESSION['MobileViewer'];
        }
        
        //Detect unit if Session and cookie is not set
        $ViewDetect = new Mobile_Detect;
        UserAccess::SetMobileViewer($ViewDetect->isMobile());
        return $_SESSION['MobileViewer'];
        
            
    }
    
    static function SetMobileViewer($viewer) {
        $_SESSION['MobileViewer'] = $viewer;
        setcookie("MobileViewer", $_SESSION['MobileViewer'], time() + 60 * 60 * 24 * 100, "/");
    }
    

    /**
     * Check if input string is a valide email-format
     * @param type $str
     * @return type 
     */
    private static function checkEmail($str) {
        return preg_match("/^[\.A-z0-9_\-\+]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $str);
    }

    /**
     * Send Email function
     * @param type $from
     * @param type $to
     * @param type $subject
     * @param type $body 
     */
    function send_mail($from, $to, $subject, $body) {
        $headers = '';
        $headers .= "From: $from\n";
        $headers .= "Reply-to: $from\n";
        $headers .= "Return-Path: $from\n";
        $headers .= "Message-ID: <" . md5(uniqid(time())) . "@" . $_SERVER['localhost'] . ">\n";
        $headers .= "MIME-Version: 1.0\n";
        $headers .= "Date: " . date('r', time()) . "\n";

        mail($to, $subject, $body, $headers);
    }

}